﻿using System;
using System.Collections.Generic;
using System.Linq;
using Models.ServerModels;
using Utils;
using System.Data;

namespace DdnsServer.DAL
{
    public class RecordService
    {
        #region 转换模型
        private UserRecordListModel DrToRecord(DataRow dr)
        {
            UserRecordListModel ur = new UserRecordListModel
            {
                domain = dr.IsNull("domain") ? "" : dr["domain"].ToString(),
                domain_id = dr.IsNull("domain_id") ? -1 : Convert.ToInt32(dr["domain_id"]),
                id = dr.IsNull("id") ? 0 : Convert.ToInt32(dr["id"]),
                line = dr.IsNull("line") ? "" : dr["line"].ToString(),
                line_id = dr.IsNull("line_id") ? "" : dr["line_id"].ToString(),
                record_id = dr.IsNull("record_id") ? -1 : Convert.ToInt32(dr["record_id"]),
                sub_domain = dr.IsNull("sub_domain") ? "@" : dr["sub_domain"].ToString(),
                uid = dr.IsNull("uid") ? 0 : Convert.ToInt32(dr["uid"]),
                api_id = dr.IsNull("api_id") ? "" : dr["api_id"].ToString(),
                api_token = dr.IsNull("api_token") ? "" : dr["api_token"].ToString(),
                last_update_date = dr.IsNull("last_update_date") ? default(DateTime) : Convert.ToDateTime(dr["last_update_date"]),
                last_update_code=dr.IsNull("last_update_code")?1:Convert.ToInt32(dr["last_update_code"]),
                last_update_ip=dr.IsNull("last_update_ip")?"127.0.0.1":dr["last_update_ip"].ToString()
            };
            return ur;
        }
        #endregion
        #region 读用户记录列表
        public List<UserRecordListModel> GetUserRecordList(int uId)
        {
            try
            {
                string sqlstr = "select * from t_recordList where uid=" + uId;
                var dt = DB.Query(sqlstr);
                if (dt.Rows.Count < 1)
                    return null;
                List<UserRecordListModel> l = new List<UserRecordListModel>();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    var dr = dt.Rows[i];
                    l.Add(DrToRecord(dr));
                }
                return l;
            }
            catch (Exception)
            {
                throw;
            }
        }
        #endregion
        #region 更新记录状态
        public void EditUserRecord(int id,string last_update_ip,int last_update_code)
        {
            try
            {
                string sqlstr = $"update t_recordList set last_update_date=datetime('now','localtime'),last_update_ip='{last_update_ip}',last_update_code={last_update_code} where id={id}";
                DB.Exec(sqlstr);
            }
            catch (Exception)
            {
                //无论是否成功，不抛异常
            }
        }
        #endregion
    }
}